package com.tornado.community.controller;

import com.tornado.community.dto.CommentDto;
import com.tornado.community.dto.QuestionDto;
import com.tornado.community.mapper.custome.MyQuestionMapper;
import com.tornado.community.model.Question;
import com.tornado.community.model.QuestionExample;
import com.tornado.community.provider.Tools;
import com.tornado.community.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Controller
public class QuestionController {
    private final MyQuestionMapper myQuestionMapper;
    private final CommentService commentService;
    private final Tools tools;

    @Autowired
    public QuestionController(MyQuestionMapper myQuestionMapper, Tools tools, CommentService commentService) {
        this.myQuestionMapper = myQuestionMapper;
        this.tools = tools;
        this.commentService = commentService;
    }

    @GetMapping("/question/{id}")
    public String question(@PathVariable("id") Integer id,
                           Model model, HttpServletRequest request) {
        //登陆检查
        tools.loginCheck(request);
        //查问题
        QuestionDto questionDto = Objects.requireNonNull(myQuestionMapper.selectQuestionById(id), "查看的问题不存在。");
        myQuestionMapper.incView(id);
        //查关联问题
        String tagCondition = questionDto.getTag().replace(",", "|");
        List<Question> relativeQuestionList = myQuestionMapper.selectQuestionListByTag(id, tagCondition);
        //查评论
        List<CommentDto> commentDtoList = commentService.selectQuestionComment(id);
        model.addAttribute("question", questionDto);
        model.addAttribute("commentList", commentDtoList);
        model.addAttribute("relativeQuestionList", relativeQuestionList);
        return "question";
    }
}
